package com.cooba.activitys.login;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.MainActivity;
import com.cooba.activitys.user.ForgetPasswordActivity;
import com.cooba.utils.Md5Utils;
import com.cooba.utils.MySqlOpenHelper;
import com.cooba.utils.ServerURL;
import com.cooba.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.List;
/**
 * Created by Administrator on 2015/12/10.
 * 登录
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {
    private TextView mLogin;
    private TextView mRegistered;
    private TextView mForgetPassword;
    private ImageView mBack_login;
    private EditText mEt_loginNumber, mEt_loginPassword;
    private String COOBA = "COOBA-YANSHI";
    private LinearLayout qq_login;
    private MySqlOpenHelper helper;
    private SQLiteDatabase database;
    private void bindViews() {
        mBack_login = (ImageView) findViewById(R.id.back_login);
        mLogin = (TextView) findViewById(R.id.login);
        mRegistered = (TextView) findViewById(R.id.registered);
        mForgetPassword = (TextView) findViewById(R.id.forgetPassword);
        mEt_loginNumber = (EditText) findViewById(R.id.et_loginNumber);
        mEt_loginPassword = (EditText) findViewById(R.id.et_loginPassword);
        qq_login = (LinearLayout) findViewById(R.id.qq_login);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        bindViews();
        mRegistered.setOnClickListener(this);
        mBack_login.setOnClickListener(this);
        mLogin.setOnClickListener(this);
        mForgetPassword.setOnClickListener(this);
        qq_login.setOnClickListener(this);
        mEt_loginNumber.setOnFocusChangeListener(this);

        getCont();
        getLocalMacAddress();
    }

    //预输入
    private void getCont() {
        helper = new MySqlOpenHelper(getApplication());
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("login_date", null, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            String login_id = cursor.getString(cursor.getColumnIndex("login_id"));
            if (login_id.equals("")) {
            } else {
                mEt_loginNumber.setText(login_id);
            }
        }
        cursor.close();
        db.close();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        final String Number = mEt_loginNumber.getText().toString();
        final String Password = Md5Utils.encodeBy32BitMD5(mEt_loginPassword.getText().toString());
        // TODO: 2015/12/14 phone ip
        /**
         * 获取手机ip地址
         */
        String PhoneIp = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();

                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        PhoneIp = inetAddress.getHostAddress().toString();
                        Log.e("mm", "getPhoneIp" + PhoneIp);
                    }
                }
            }
        } catch (Exception e) {

        }


        switch (v.getId()) {
            //立即注册
            case R.id.registered:
                intent = new Intent(LoginActivity.this, RegisteredActivity.class);
                startActivity(intent);
                finish();
                break;
            //返回游客登录
            case R.id.back_login:
                intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                break;

            //登录
            case R.id.login:
                if (Number.length() > 0 && Password.length() > 0) {
                    GetLoginInfo(Number, Password, PhoneIp);
                } else {
                    if (Number.length() == 0) {
                        Toast.makeText(getApplication(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    }
                    if (Password.length() == 0) {
                        Toast.makeText(getApplication(), "请输入密码", Toast.LENGTH_SHORT).show();
                    }
                }
                break;

            //忘记密码
            case R.id.forgetPassword:
                intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
                finish();
                break;


            //QQ登录
            case R.id.qq_login:

                break;
        }
    }

    /**
     * 使用xutils获取登陆接口数据
     **/
    private void GetLoginInfo(String number, String password, String wifiip) {
        // TODO: 2015/12/13 获取系统时间
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String create_date = sDateFormat.format(new java.util.Date());
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("login_id", number);
        params.addQueryStringParameter("password", password);
        params.addQueryStringParameter("login_ip", wifiip);
        params.addQueryStringParameter("login_date", create_date);
        Log.e("ssssss", "number" + number + "  wifiip" + wifiip + "  password" + password + "  create_date" + create_date);
        String url = ServerURL.httpUrl + ServerURL.Login;
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("ss", "链接服务器成功");
                String result = null;
                //JSON的解析过程
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                    result = jsonObject.get("status").toString();
                    String name = jsonObject.get("name").toString();
                    String login_id = jsonObject.get("login_id").toString();
                    String phone = jsonObject.get("phone").toString();
                    Log.e("status", "result" + result);
                    if (result.equals("0")) {
                        Toast.makeText(LoginActivity.this, "登陆失败，用户名或密码错误!", Toast.LENGTH_LONG).show();
                    } else if (result.equals("1")) {

                        Toast.makeText(LoginActivity.this, "登陆成功!", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        //todo 存入数据库
                        ContentValues value = new ContentValues();
                        value.put("login_id", login_id);
                        value.put("name", name);
                        value.put("phone", phone);

                        helper = new MySqlOpenHelper(getApplication());
                        database = helper.getWritableDatabase();
                        database.delete("login_date", null, null);
                        database.insert("login_date", null, value);
                        helper.close();
                        database.close();
                        finish();
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(LoginActivity.this, "链接服务器失败", Toast.LENGTH_LONG).show();
                Log.e("ss", "链接服务器失败");
            }
        });
    }

    //手机号码校验
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
        } else {
            if (Utils.isnumber(mEt_loginNumber.getText().toString())) {
            } else {
                Toast.makeText(getApplication(), "请输入正确手机号", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //mac获取
    public String getLocalMacAddress() {
        String bssid = "";
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        List wifiList = wifi.getScanResults();
        for (int i = 0; i < wifiList.size(); i++) {
            ScanResult result = (ScanResult) wifiList.get(i);
            String ssid = result.SSID;
            if ("COOBA-YANSHI".equals("")) {
            } else if ("COOBA-YANSHI".equals(result.SSID)) {
                bssid = result.BSSID;
                Log.e("mmmm", "bssid=" + bssid);
                String bssid0 = bssid.replace(":", "").trim();
                Long bssid1 = Long.parseLong(bssid0, 16);
                String s = Long.toHexString(bssid1 - 1l).toUpperCase();
                String mac = null;
                if (s.length() == 9) {
                    String s2 = "0" + s;
                    StringBuffer s3 = new StringBuffer(s2);
                    for (int j = 2; j < s3.length(); j += 3) {
                        s3.insert(j, ":");
                    }

                    mac = "00:" + s3;
                    Log.e("mmmm", mac);
                } else if (s.length() == 10) {
                    String s2 = s;
                    StringBuffer s3 = new StringBuffer(s2);
                    for (int j = 2; j < s3.length(); j += 3) {
                        s3.insert(j, ":");
                    }

                    mac = "00:" + s3;
                    Log.e("mmmm", mac);
                }
            }
        }
        return bssid;
    }
}
